package de.se.ludoapp.activity.task;

import android.os.AsyncTask;
import android.widget.TextView;
import de.se.ludoapp.LudoApplication;
import de.se.ludoapp.R;
import de.se.ludoapp.activity.NewGameActivity;
import de.se.ludoapp.gaming.Game;
import de.se.ludoapp.response.GameResponse;

/**
 * Task to create a new game at the server.
 * 
 * @author Marlen Rotert
 * 
 */
public class NewGameTask extends AsyncTask<String, Integer, String> {

	private LudoApplication ludoApp;
	private NewGameActivity context;
	private Game game;

	public NewGameTask(LudoApplication ludoApp, NewGameActivity context) {
		super();
		this.ludoApp = ludoApp;
		this.context = context;
		this.game = null;
	}

	/**
	 * Create a new Game on Server.<br>
	 * This method is executed in a concurrent thread (asynchronous). Therefore
	 * you mustn't accessed on view elements!
	 */
	@Override
	protected String doInBackground(String... params) {
		/* Execute openNewGame */
		GameResponse gameResponse = ludoApp.getLudoStub().openNewGame(
				ludoApp.getlogedinUser().getSessionId());
		if (gameResponse.getReturnCode() == 0) {
			game = gameResponse.getGame();
			ludoApp.setCurrentGame(game);
		}
		return gameResponse.getMsg();
	}

	/**
	 * Show the new game with playerYellow. <br>
	 * This method is invoked when the OpenGameTask is executed. You are only
	 * allowed here to access on view Elements (TextView and Buttons)!
	 */
	@Override
	protected void onPostExecute(String result) {
		if (game != null) {
			context.updateView();
		} else {
			TextView textView = (TextView) context
					.findViewById(R.id.textViewNewGameHead);
			textView.setText(textView.getText() + " " + result);
		}
	}
}
